// pages/shopcar/shopcar.js
const app = getApp()
var initdata = function(that) {
  var list = that.data.list
  console.log(list) 
  if (list) {
    for (var i = 0; i < list.length; i++) {
      list[i].shows = ""
    }
    that.setData({
      list: list
    })
  }

}
Page({
  data: {
    allchecked: true,
    numval: 1,
    delBtnWidth: 360, //删除按钮宽度单位（rpx） 
    // 列表数据
    list: '',
    total: ''
  },

  onLoad: function(options) {
    this.initEleWidth();
    if (wx.getStorageSync('token') == '') {
      this.setData({
        list: '',
      })
    } else {
      this.getlist();
    }

  },
  onShow() {
    this.getlist();
  },
  // 开始滑动事件
  touchS: function(e) {
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置 
        startX: e.touches[0].clientX
      });
    }
  },
  // touchM: function (e) {
  //   var that = this;
  //   initdata(that)
  //   if (e.touches.length == 1) {
  //     //手指移动时水平方向位置 
  //     var moveX = e.touches[0].clientX;
  //     //手指起始点位置与移动期间的差值 
  //     var disX = this.data.startX - moveX;
  //     var delBtnWidth = this.data.delBtnWidth;
  //     // var txtStyle = "";
  //     if (disX == 0 || disX < 0) { //如果移动距离小于等于0，文本层位置不变 
  //       // txtStyle = "left:0px";
  //     } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离 
  //       // txtStyle = "left:-" + disX + "px";
  //       if (disX >= delBtnWidth) {
  //         //控制手指移动距离最大值为删除按钮的宽度 
  //         // txtStyle = "left:-" + delBtnWidth + "px";
  //       }
  //     }

  //   }
  // },
  // 滑动中事件
  touchE: function(e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置 
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离 
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮 
      var txtStyle = "";
      txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
      //获取手指触摸的是哪一项 
      var index = e.currentTarget.dataset.index;
      var list = this.data.list;
      list[index].shows = txtStyle;
      // console.log("1", list[index].shows);
      //更新列表的状态 
      this.setData({
        list: list
      });
    } else {
      console.log("2");
    }
  },
  //获取元素自适应后的实际宽度 
  getEleWidth: function(w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2);
      // console.log(scale); 
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error 
    }
  },
  initEleWidth: function() {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },
  //点击删除按钮事件 
  delItem: function(e) {
    var that = this;
    var list = that.data.list;
    wx.showModal({
      title: '提示',
      confirmText: '确定',
      confirmColor: '#28A8F9',
      showCancel: true,
      content: '是否删除此商品？',
      success: function(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
          })
          wx.request({ //获取购物车列表
            url: app.globalData.url + '/jxb/goods/goods/delShopCart',
            method: 'GET',
            data: {
              token: wx.getStorageSync('token'),
              sonid: e.currentTarget.dataset.sonid,
              status: '1'
            },
            success: function(res) {
              wx.hideLoading();
              if (res.data.code == 0) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000
                });
                let list = that.data.list;
                list.splice(e.currentTarget.dataset.index, 1)
                that.setData({
                  list: list
                })
                that.getlist();
              } else {
                wx.showToast({
                  title: '网络错误',
                  icon: 'none',
                  duration: 2000
                })
              }
            },
            fail: function() {
              wx.showToast({
                title: '网络错误',
                icon: 'none',
                duration: 2000
              })
            }

          })

        } else if (res.cancel) {
          return;
        }
      }
    })
    // 重新渲染
    that.setData({
      list: list
    });
    initdata(that)
  },
  editItem: function(e) { //编辑修改
    let json = e.currentTarget.dataset.index;
    console.log(json);
    wx.navigateTo({
      url: '/pages/upimg/upimg?type=car&josn=' + JSON.stringify(json),
    })
  },

  radioval: function(e) { //单选按钮
    let index = e.currentTarget.dataset.index;
    var list = this.data.list;
    // list[index].checked = !list[index].checked
    if (list[index].checked == 1) {
      list[index].checked = 2
    } else {
      list[index].checked = 1
    }
    let that = this;
    that.setData({
      allchecked: list.every(function(item) {
        return item.checked == true;
      }),
      list: list
    })
     that.getlist();
     initdata(that)

  },
  allchcked: function(e) { //全选
    this.setData({
      allchecked: !this.data.allchecked
    })
    if (this.data.allchecked == true) {
      for (var i = 0; i < this.data.list.length; i++) { //全选
        this.data.list[i].checked = 1
      }
      this.setData({
        list: this.data.list
      })
      this.getlist();
    } else {
      for (var i = 0; i < this.data.list.length; i++) { //取消全选
        this.data.list[i].checked = 2
      }
      this.setData({
        list: this.data.list
      })
      this.getlist();
    }
  },
  getlist() {
    let _that = this;
    let list = '';
    if (this.data.list.length !== 0) {
      list = this.data.list;
      list = JSON.stringify(list)
    } else {
      list = ''
    }
    wx.request({ //获取购物车列表
      url: app.globalData.url + '/jxb/goods/goods/getCartGoods',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        token: wx.getStorageSync('token'),
        jsonlist: list
      },
      success: function(res) {
        console.log(res)
        if (res.data.data == 0) {
          _that.setData({
            allchcked: false
          })
        } else if (res.data.code == 402) {
          _that.setData({
            allchcked: false,
            list: '',
          })
        } else if (res.data.code == 0) {
          _that.setData({
            list: res.data.data.list,
            total: res.data.data.total,
            allchecked: res.data.data.list.every(function(item) {
              return item.checked == true;
            }),
          })
        }
      },

    })
  },

  downnum: function(e) { //数量减  
    let index = e.currentTarget.dataset.index;
    var list = this.data.list;
    console.log(list[index].num)
    if (list[index].num > 1) {
      list[index].num--
        this.setData({
          list: list
        });
      this.getlist();
    }
  },
  addnum: function(e) { //数量加
    let index = e.currentTarget.dataset.index;
    console.log(index)
    var list = this.data.list;
    list[index].num++
      this.setData({
        list: list
      })
    this.getlist();

  },
  paymoney() { //购物车结算
   console.log(this.data.list)
    for (var i = 0; i < this.data.list.length;i++){
      if (this.data.list[i].checked==1){
        wx.navigateTo({
          url: '/pages/paymoney/paymoney?type=bycar',
        })
      }else{
        wx:wx.showToast({
          title: '请选中商品',
          icon: 'none',
        })
      }
    }
  return;
  
  },
  goindex() {
    wx.navigateTo({
      url: '/pages/persondz/persondz',
    })
  },
  seeview(e) {//预览图片
    let pidiurl = e.currentTarget.dataset.pidiurl
    var index = e.currentTarget.dataset.index;
    wx.previewImage({
      urls: [pidiurl],
    })
  },
  addorder() { //继续添加
    wx.navigateTo({
      url: '/pages/persondz/persondz',
    })
  },
})